/**************************************************
获取分数-绩效合同
* */
<template>
  <div class="mod-config">
    <basic-container>
      <div v-if="hideScoreView">
        <div>
          <div :height="searchheight">
          <span style="float:right;margin-top:-20px;margin-bottom:20px;cursor: pointer;" @click="searchchangeadvanced">
            {{ searchadvanced ? "查询条件收起" : "查询条件展开" }}
            <i :class="searchadvanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"/>
          </span>
            <div v-show="searchadvanced">
              <el-form
                :inline="true"
                :model="searchForm"
                @keyup.enter.native="getDataList()"
                class="form-inline">
                <el-form-item label="统计名称">
                  <selectSearch @getDataByTjmc="getDataByTjmc"></selectSearch>
                </el-form-item>
                <el-form-item>
                  <el-button
                    icon="el-icon-search"
                    type="primary"
                    class="marginLeft"
                    @click="getDataList()"
                  >检索</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="boxContain" >
            <!--操作按钮-->
            <div>
              <el-button type="primary" @click="addAndEditOpera()">新增</el-button>
            <!--  <el-button type="danger" @click="delData()" :disabled="canDelete">删除</el-button>-->
            </div>
            <div>
<!--              <el-button type="primary" @click="exportXlsx">模板下载</el-button>-->
              <el-button type="primary" @click="exportExcel()">导出</el-button>
            </div>
          </div>
          <div class="mt10">
            <el-radio-group v-model="tabType" @input="changeTabType">
              <el-radio :label="`0`">人员</el-radio>
              <el-radio :label="`1`">机构</el-radio>
            </el-radio-group>
          </div>

          <!--数据列表-->
          <el-table
            style="width: 100%;margin-top:20px"
            :data="dataList"
            border
            header-align="center"
            v-loading="dataListLoading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column type="index" width="55" align="center"  label="序号" ></el-table-column>
            <el-table-column prop="tjmc" align="center" min-width="100" label="统计名称" show-overflow-tooltip>
              <template slot-scope="scope">
                  <span
                    @click="addAndEditOpera(scope.row)"
                    style="color:rgb(14, 37, 140);cursor:pointer"
                  >{{scope.row.hzzqmc}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="bz" align="center"  label="备注" show-overflow-tooltip></el-table-column>
            <el-table-column prop="dataTqsj" align="center"  label="数据提取时间" min-width="110" show-overflow-tooltip>
              <template slot-scope="scope">
                {{scope.row.startDate}}至{{scope.row.endDate}}
              </template>
            </el-table-column>
            <el-table-column prop="state" align="center"  label="状态">
              <template slot-scope="scope">
                {{scope.row.state|transState(scope.row.lx)}}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" align="center"  label="创建时间"></el-table-column>
            <el-table-column align="center"  fixed="right" label="操作" min-width="100">
              <template slot-scope="scope">
                <div style="display: flex;justify-content: center">
                  <div style="display: flex;width: 100%;justify-content: center">
                    <!--<el-button
                         type="primary"
                         plain
                         size="small"
                         @click="openImport(scope.row)">导入数据</el-button>-->
                    <el-button
                      type="primary"
                      plain
                      size="small"
                      @click="showScoreView(scope.row)">生成得分</el-button>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!--分页-->
          <div class="avue-crud__pagination">
            <el-pagination
              @size-change="sizeChangeHandle"
              @current-change="currentChangeHandle"
              :current-page="pageData.pageIndex"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageData.pageSize"
              :total="pageData.totalPage"
              background
              layout="total, sizes, prev, pager, next, jumper"
            ></el-pagination>
          </div>
        </div>
        <addAndEditDialog ref="addEditDialogShow" v-if="addEditDialogShow" @refreshDataList="refreshDataList"></addAndEditDialog>
        <!--导入-->
        <el-dialog width="40%" title="导入" :visible.sync="innerVisible" append-to-body>
          <el-row class="mb10" style="height: 10vh;" :gutter="10">
            <el-col :span="4">
              <el-upload
                style="margin-left: 8px;"
                class="upload-demo"
                action
                :on-change="handleChange"
                :show-file-list="false"
                :on-remove="handleRemove"
                :file-list="fileListUpload"
                :limit="limitUpload"
                accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                :auto-upload="false"
              >
                <el-button type="primary" plain class="fr">导入</el-button>
              </el-upload>
            </el-col>
          </el-row>
        </el-dialog>

      </div>
      <div v-else>
         <getScoreView @closeDialog="closeDialog" ref="scoreView"></getScoreView>
      </div>
    </basic-container>
  </div>
</template>

<script>
    import addAndEditDialog from "@/views/statisticsanalysis/components/addAndEditDialog";
    import selectSearch from "@/views/statisticsanalysis/components/selectSearch";
    import getScoreView from "@/views/statisticsanalysis/components/getScoreView";
    // 接口 api
    import {fractionList, scoreExportExcel,importPfData,transState} from "@/api/statisticsanalysis/fractionGet.js";
    import { mapGetters} from "vuex";
    import store from "@/store";
    export default {
        data(){
            return {
                headers: {
                    Authorization: "Bearer " + store.getters.access_token
                },
                searchForm: {isld:'0'}, //查询表单
                canDelete: true, // 删除表格数据的禁用
                multipleSelection: [], //表格中被选中的数据
                dataList: [],
                dataListLoading: false,
                searchadvanced: true,
                searchheight: "0",
                addEditDialogShow:false,
                menuType:'pf', //ht rckh pf zdrw gzrws
                hideScoreView:true,
                pageData: {
                    //分页对象
                    pageIndex: 1,
                    pageSize: 10,
                    totalPage: 0
                },
                innerVisible:false,
                limitUpload: 3,
                fileListUpload: [],
                accountList: [],
                sftqId:'',
                tabType:'0'
            };
        },
        components: {
            selectSearch,//下拉选搜索组件
            addAndEditDialog,
            getScoreView//生成得分的组件
        },
        filters: {
            transState
        },
        computed: {
            ...mapGetters(["permissions"])
        },
        watch: {

        },
        created() {
            this.getDataList();
        },
        methods: {
            //选择统计名称执行搜索功能
            getDataByTjmc(tjmc){
                this.searchForm.hzzqmc = tjmc ;
                this.getDataList() ;
            },
            //新增或者编辑操作
            addAndEditOpera(obj) {
                this.addEditDialogShow = true;
                this.$nextTick(() => {
                    if (obj){
                        this.$refs.addEditDialogShow.init(obj,this.menuType,'edit',this.tabType);
                    }else{
                        this.$refs.addEditDialogShow.init('',this.menuType,'add',this.tabType);
                    }
                });
            },
            showScoreView(row){
                this.hideScoreView = false ;
                this.$nextTick(() => {
                    this.$refs.scoreView.init(row.id,this.menuType,this.tabType);
                })
            },
            // 删除数据
            delData() {
                // 删除只能删除状态为0  1 的数据
                this.$confirm("此操作将删除选中的数据, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        let ids = this.multipleSelection.map(it => {
                            return it.id;
                        });
                        deleteChoose(ids.toString()).then(r => {
                            if (r.data.code == 0) {
                                this.$message.success("删除成功");
                                this.getDataList();
                            } else {
                                this.$message.error(r.data.msg);
                                this.getDataList();
                            }
                        });
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除"
                        });
                    });
            },
            // 勾选数据
            handleSelectionChange(val) {
                if (val.length == 0) {
                    this.canDelete = true;
                } else{
                    this.canDelete = false ;
                }
                this.multipleSelection = val;
            },
            // 查询条件的展开关闭
            searchchangeadvanced() {
                this.searchadvanced = !this.searchadvanced;
                if (this.searchadvanced) {
                    this.searchheight = "auto";
                }
            },

            // 获取数据列表
            getDataList() {
                this.dataListLoading = true;
                this.searchForm.lx = this.menuType ;
                this.searchForm.type = this.tabType ;
                fractionList(
                    Object.assign(
                        {
                            current: this.pageData.pageIndex,
                            size: this.pageData.pageSize,
                        },
                        this.searchForm
                    )
                )
                    .then(r => {
                        if (r.data.code == 0) {
                            this.dataListLoading = false ;
                            this.dataList = r.data.data.records ;
                            this.pageData.totalPage = r.data.data.total;
                        }
                    })
                    .catch(err => {});
            },
            //刷新界面
            refreshDataList(){
                this.getDataList() ;
            },
            // 关闭弹窗
            closeDialog() {
                this.getDataList() ;
                this.hideScoreView = true ;
            },
            //导出
            exportExcel(){
                let data = this.multipleSelection;
                if (data.length == 0) {
                    this.$message.closeAll();
                    this.$message.warning("请选择一个工作！");
                    return;
                }
                let filename = "评分数据" + ".xlsx";
                let ids = [];
                for (let i = 0; i < data.length; i++) {
                    ids.push(data[i].id);
                }
                scoreExportExcel({
                    ids: ids
                }).then(response => {
                    this.$message.closeAll();
                    this.$message.success("导出成功!");
                    let url = window.URL.createObjectURL(new Blob([response.data]));
                    let link = document.createElement("a");
                    link.style.display = "none";
                    link.href = url;
                    link.setAttribute("download", filename);
                    document.body.appendChild(link);
                    link.click();
                });
            },
            // 条数变化
            sizeChangeHandle(val) {
                this.pageData.pageSize = val;
                this.pageData.pageIndex = 1 ;
                this.getDataList();
            },
            // 页码分页变化
            currentChangeHandle(val) {
                this.pageData.pageIndex = val;
                this.getDataList();
            },
            // excel表上传
            handleChange(file, fileList) {

                this.fileTemp = file.raw;
                let fileName = file.raw.name;
                let fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                // 判断上传文件格式
                if (this.fileTemp) {
                    if (fileType == "xlsx" || fileType == "xls") {
                        this.importf(this.fileTemp);
                        this.innerVisible = false;

                    } else {
                        this.$message({
                            type: "warning",
                            message: "附件格式错误，请删除后重新上传！"
                        });
                    }
                } else {
                    this.$message({
                        type: "warning",
                        message: "请上传附件！"
                    });
                }
            },
            openImport(row) {
                this.sftqId = row.id ;
                this.innerVisible = true;
            },
            // 移除excel表
            handleRemove(file, fileList) {
                this.fileTemp = null;
            },
            //导入的方法
            importf(obj) {
                this.dialogVisible = true;
                var _this = this;
                let inputDOM = this.$refs.inputer; // 通过DOM取文件数据
                this.file = event.currentTarget.files[0];
                let rABS = false; //是否将文件读取为二进制字符串
                let f = this.file;
                let reader = new FileReader();
                //if (!FileReader.prototype.readAsBinaryString) {
                FileReader.prototype.readAsBinaryString = function(f) {
                    let binary = "";
                    let rABS = false; //是否将文件读取为二进制字符串
                    let pt = this;
                    let wb; //读取完成的数据
                    let outdata;
                    let reader = new FileReader();
                    reader.onload = function(e) {
                        let bytes = new Uint8Array(reader.result);
                        let length = bytes.byteLength;
                        for (let i = 0; i < length; i++) {
                            binary += String.fromCharCode(bytes[i]);
                        }
                        let XLSX = require("xlsx");
                        if (rABS) {
                            wb = XLSX.read(btoa(fixdata(binary)), {
                                //手动转化
                                type: "base64"
                            });
                        } else {
                            wb = XLSX.read(binary, {
                                type: "binary"
                            });
                        }
                        // outdata就是你想要的东西 excel导入的数据
                        outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);

                       let result = outdata.map(item => {
                           return { ygbm: item.__EMPTY, ygname:item.__EMPTY_1,sumScore: item.__EMPTY_2}
                       } ) ;
                        result.shift() ; //删除数组第一行数据
                        console.log("result")
                        console.log(result)


                        // excel 数据再处理
                        // let arr = [];
                        // outdata.map(v => {
                        //     // let jsonString = JSON.stringify(v).replace(/\*/g, '').replace(/\s/ig,'');
                        //     let jsonString = JSON.stringify(v).replace(/\//g, "").replace(/\s/gi, "");
                        //     v = JSON.parse(jsonString);
                        //     let obj = {};
                        //     obj.ygbm = v.员工编号;
                        //     obj.ygname = v.姓名;
                        //     obj.sumScore = v.总分;
                        //     arr.push(obj);
                        // });
                        // _this.accountList = [...arr];

                        importPfData( result,_this.sftqId).then(r => {
                            console.log(r);
                            if(r.data.data.length != 0){
                                let data = r.data.data;
                                _this.$message.success("导入成功");
                                _this.getDataList() ;
                            }else{
                                _this.$message.error("导入失败");
                            }

                        }).catch(error => {
                            console.log(error);
                        });
                    };
                    reader.readAsArrayBuffer(f);
                };
                if (rABS) {
                    reader.readAsArrayBuffer(f);
                } else {
                    reader.readAsBinaryString(f);
                }
            },
            //模板下载
            exportXlsx() {
                this.$message.closeAll();
                this.$message.success("下载成功!");
                window.location.href = "../../static/cepinginfo.xlsx";
            },
            changeTabType(){
              this.pageData.pageIndex = 1 ;
              this.getDataList();
            }
        }
    };
</script>

<style lang="scss" scoped>
 .boxContain{padding-bottom: 10px;border-bottom:1px solid rgb(176, 189, 226);display: flex;justify-content: space-between;width: 100%}
</style>
